//
//  ResourceLoader.m
//  ResourceLoader
//
//  Created by winston on 13-4-10.
//  Copyright (c) 2013年 winston. All rights reserved.
//

#import "ResourceLoader.h"
#import "../../HondaPro_2/aejoy/ConfigCodeHelper.h"
#import "JSONKit.h"

@interface ResourceLoader (PrivateMethods)

-(BOOL)isFileExist:(NSString*)filePath;
-(BOOL)isDirectoryExist:(NSString*)directoryPath;

@end

@implementation ResourceLoader

static ResourceLoader * _instance;

+(ResourceLoader*)getInstance
{
    @synchronized(self)
    {
        if(_instance == nil)
            _instance = [ResourceLoader new];
    }
    return _instance;
}

-(id)init
{
    self = [super init];
    if(self)
    {
        fileManager =    [NSFileManager new];
        autoDictionary = [NSMutableDictionary new];
    }
    return self;
}

-(void)RefreshAutoDics
{
    [autoDictionary removeAllObjects];
    
    NSDictionary * cars = [[ConfigCodeHelper shareInstance].sourceDic objectForKey:@"cars"];
    
    NSString * documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString * documentsAutosPath = [NSString stringWithFormat:@"%@/%@",documentsPath,@"Autos"];
    
    NSError *error = nil;
    
    //存在Document Autos目录,该目录优先级高
    if([self isDirectoryExist:documentsAutosPath])
    {
        NSArray* files = [fileManager contentsOfDirectoryAtPath:documentsAutosPath error:&error];
        
        if(error == nil)
        {
            for (NSInteger index=0; index < [files count]; index++)
            {
                NSString* fileName = [files objectAtIndex:index];
                
                NSString *path = [documentsAutosPath stringByAppendingPathComponent:fileName];
                if([self isDirectoryExist:path])
                {
                    if ([cars objectForKey:[NSString stringWithFormat:@"%@.zip",fileName]]) {
                        [autoDictionary setObject:[NSDictionary dictionaryWithObjectsAndKeys:fileName,@"autoid",path,@"autopath",nil] forKey:fileName];
                    }
                }
            }
        }
    }
    
    NSString * defaultPath = [[[NSBundle mainBundle]bundlePath]stringByAppendingPathComponent:@"AutoResource"];
    NSString * defaultAutosPath = [NSString stringWithFormat:@"%@/%@",defaultPath,@"Autos"];
    
    //存在AutoResource Autos目录,该目录优先级低
    NSArray* files = [fileManager contentsOfDirectoryAtPath:defaultAutosPath error:&error];
    for (NSInteger index=0; index < [files count]; index++)
    {
        NSString* fileName = [files objectAtIndex:index];
        
        NSString *path = [defaultAutosPath stringByAppendingPathComponent:fileName];
        
        if([self isDirectoryExist:path])
        {
            if([autoDictionary objectForKey:fileName]==nil)
            {
                if ([cars objectForKey:[NSString stringWithFormat:@"%@.zip",fileName]]) {
                    [autoDictionary setObject:[NSDictionary dictionaryWithObjectsAndKeys:fileName,@"autoid",path,@"autopath",nil] forKey:fileName];
                }
                //                    [autoDictionary setObject:[NSDictionary dictionaryWithObjectsAndKeys:fileName,@"autoid",path,@"autopath",nil] forKey:fileName];
            }
        }
    }
    
    
//    NSLog(@"autoDictionary(%@)  @@%s", autoDictionary, __func__);
    
    NSString * documentDbPath = [NSString stringWithFormat:@"%@/paddata/%@",documentsPath,@"model.sqlite"];
    NSString * defaultDbPath = [NSString stringWithFormat:@"%@/paddata/%@",defaultPath,@"model.sqlite"];
    NSString * dbPath = [self isFileExist:documentDbPath]?documentDbPath:defaultDbPath;
    sqliteHelper = [SQLiteHelper getInstance];
    if (sqliteHelper) {
        [sqliteHelper closeDatabase];
        [sqliteHelper openDatabase:dbPath];
    }
}

-(NSArray*)getAutoArray
{
    return [autoDictionary allKeys];
}

-(NSArray*)getTemplatesByPath:(NSString *)path
{
    NSError * error = nil;
    
   	NSArray* files = [fileManager contentsOfDirectoryAtPath:path error:&error];
	
    if(error != nil)
        return nil;
	
	NSMutableArray* resultArray = [NSMutableArray new];
	
	for (NSInteger index=0; index < [files count]; index++)
	{
		NSString* fileName = [files objectAtIndex:index];
		NSString* extType = [fileName pathExtension];
		if(NO == [extType isEqualToString:@"tpl"])
			continue;
		[resultArray addObject:fileName];
	}
	return [resultArray autorelease];
}

-(NSArray*)getTemplatesByKey:(NSString*)moduleKey withAutoID:(NSString*)autoID
{
    NSString * modulePath = [self getModulePathByKey:moduleKey withAutoID:autoID];
    
    DFLog(@"ModulePath==========:%@",modulePath);
    
    NSError * error = nil;
    
   	NSArray* files = [fileManager contentsOfDirectoryAtPath:modulePath error:&error];
	
    if(error != nil)
        return nil;
	
	NSMutableArray* resultArray = [NSMutableArray new];
	
	for (NSInteger index=0; index < [files count]; index++)
	{
		NSString* fileName = [files objectAtIndex:index];
		NSString* extType = [fileName pathExtension];
		if(NO == [extType isEqualToString:@"tpl"])
			continue;
		[resultArray addObject:fileName];
	}
	return [resultArray autorelease];
}

-(NSString*)getModulePathByKey:(NSString*)moduleKey  withAutoID:(NSString*)autoID;
{
    
    NSString * autoPath = [[autoDictionary objectForKey:autoID]objectForKey:@"autopath"];
    NSString * modulePath = [NSString stringWithFormat:@"%@/%@",autoPath,moduleKey];
    return modulePath;
}

-(NSArray*)getFavoriteTemplatesByPath:(NSString*)path
{

    DFLog(@"getFavoriteTemplatesByPath==========:%@",path);
    
    NSError * error = nil;
    
   	NSArray* files = [fileManager contentsOfDirectoryAtPath:path error:&error];
	
    if(error != nil)
        return nil;
	
	NSMutableArray* resultArray = [NSMutableArray new];
	
	for (NSInteger index=0; index < [files count]; index++)
	{
		NSString* fileName = [files objectAtIndex:index];
		NSString* extType = [fileName pathExtension];
		if(NO == [extType isEqualToString:@"tpl"])
			continue;
		[resultArray addObject:fileName];
	}
	return [resultArray autorelease];
}

-(NSArray*)getCarBasicParas
{
    NSMutableArray * result = [NSMutableArray new];
    FMResultSet * rs = [sqliteHelper  syncExecuteQuery:SQL_GETSPECDIC];
    while([rs next])
    {
        [result addObject:[rs resultDict]];
    }
    return [result autorelease];
}


//得到车型的配置
-(NSArray*)getCarBasicParasByCarSpecId:(NSInteger)specId
{
    NSMutableArray * result = [NSMutableArray new];
    FMResultSet * rs = [sqliteHelper  syncExecuteQuery:[NSString stringWithFormat:SQL_GETSPECDATA,specId]];
    while([rs next])
    {
        [result addObject:[rs resultDict]];
    }
    return [result autorelease];
}


//得到首页车型的图片
-(NSArray*)getHomePageAutoData
{
    NSMutableArray * result = [NSMutableArray new];
    
    //@hanhaidi@0828@车型展示按特定顺序
    //    NSArray * autoValues = [autoDictionary allValues];
    //    for(NSDictionary * dic in autoValues)
    //    {
    //        NSString * imgPath = [NSString stringWithFormat:@"%@/Home/Auto.png",[dic objectForKey:@"autopath"]];
    //        NSString * logoPath = [NSString stringWithFormat:@"%@/Home/Logo.png",[dic objectForKey:@"autopath"]];
    //        [result addObject:[NSDictionary dictionaryWithObjectsAndKeys:
    //                           [dic objectForKey:@"autoid"],@"autoid",imgPath,@"homeimage",logoPath,@"LogoPath",nil]];
    //    }
    NSArray* autoArr = [[ConfigCodeHelper shareInstance].codeADic objectForKey:@"sortCars"];
    for (int i=0; i<[autoArr count]; i++) {
        NSString* key = [autoArr objectAtIndex:i];
        NSDictionary* dic = [autoDictionary objectForKey:key];
        if (dic) {
            NSString * imgPath = [NSString stringWithFormat:@"%@/Home/Auto.png",[dic objectForKey:@"autopath"]];
            NSString * logoPath = [NSString stringWithFormat:@"%@/Home/Logo.png",[dic objectForKey:@"autopath"]];
            [result addObject:[NSDictionary dictionaryWithObjectsAndKeys:
                               [dic objectForKey:@"autoid"],@"autoid",imgPath,@"homeimage",logoPath,@"LogoPath",nil]];
        }
    }
    
    NSLog(@"result = %@",result);
    return [result autorelease];
}

//得到首页车型的图片路径
-(NSString*)getHomePageAutoImagePath:(NSString *)autoId
{
    NSDictionary * dic = [autoDictionary objectForKey:autoId];
    NSString * imgPath = [NSString stringWithFormat:@"%@/Home/Auto.png",[dic objectForKey:@"autopath"]];

    return imgPath;
}

//得到车型广告视频位置
-(NSString*)getADVideosPath:(NSString*)autoId WithType:(int)type
{
    NSString * videopath = nil;
    NSDictionary * dic = [autoDictionary objectForKey:autoId];
    NSString * path = [NSString stringWithFormat:@"%@/ADS/Videos/AD_%d",[dic objectForKey:@"autopath"],type];
    
    NSError * error = nil;
    
   	NSArray* files = [fileManager contentsOfDirectoryAtPath:path error:&error];
	
    if(error != nil)
        return nil;
	
	for (NSInteger index=0; index < [files count]; index++)
	{
		NSString* fileName = [files objectAtIndex:index];
		NSString* extType = [fileName pathExtension];
		if(YES == [extType isEqualToString:@"mp4"]||YES == [extType isEqualToString:@"mov"])
        {
            videopath = [NSString stringWithFormat:@"%@/%@",path,fileName];
            break;
        }
	}
    
	return videopath;
}

//获取车型广告文件名
-(NSString*)getADVideosFileName:(NSString*)autoId type:(NSInteger)type {
    NSString * videopath = nil;
    NSDictionary * dic = [autoDictionary objectForKey:autoId];
    
    NSString* path = [NSString stringWithFormat:@"%@/ADS/Videos/AD_%d/video.tpl", [dic objectForKey:@"autopath"], type];
    NSData * data = [NSData dataWithContentsOfFile:path];
    NSDictionary * tplDic = [data objectFromJSONData];
    
    NSString* extType = [[tplDic objectForKey:@"filename"] pathExtension];
    if(YES == [extType isEqualToString:@"mp4"]||YES == [extType isEqualToString:@"mov"])
    {
        videopath = [tplDic objectForKey:@"filename"];
    }
    
	return videopath;
}

-(NSString*)get360Replace:(NSString *)autoId
{
    NSDictionary * autoDic = [autoDictionary objectForKey:autoId];
    NSString * img360Path = [NSString stringWithFormat:@"%@/360_Appear_Replace",[autoDic objectForKey:@"autopath"]];
    if(![self isDirectoryExist:img360Path])
        return nil;
    NSError *error = nil;
    
//    NSArray* files = [fileManager contentsOfDirectoryAtPath:img360Path error:&error];
    
    NSString *path = nil;
    
    if(error == nil)
    {
        path = [NSString stringWithFormat:@"%@/Replace.png",img360Path];
        
    }
    return path;
}

//得到某个车型的360度外观数据
-(NSArray*)get360Appear:(NSString*)autoId
{

    
    NSDictionary * autoDic = [autoDictionary objectForKey:autoId];
    NSString * img360Path = [NSString stringWithFormat:@"%@/360_Appear",[autoDic objectForKey:@"autopath"]];
    
    if(![self isDirectoryExist:img360Path])
        return nil;
    
    NSMutableArray * result = [NSMutableArray new];
    NSError *error = nil;

    NSArray* files = [fileManager contentsOfDirectoryAtPath:img360Path error:&error];
        
    if(error == nil)
    {
        //判断是否有color.tpl文件存在
        NSData * data = [NSData dataWithContentsOfFile:[NSString stringWithFormat:@"%@/color.tpl",img360Path]];
        NSArray * templatearray = [data objectFromJSONData];
        if (templatearray)
        {
            
            for (NSInteger index=0; index < [templatearray count]; index++)
            {
                NSDictionary * temp = [templatearray objectAtIndex:index];
                NSString* fileName = [temp objectForKey:@"DocumentName"];
                NSString* colorName = [temp objectForKey:@"Title"];
                
                NSString *path = [img360Path stringByAppendingPathComponent:fileName];
                
                if([self isDirectoryExist:path])
                {
                    NSMutableDictionary * dic = [NSMutableDictionary dictionaryWithCapacity:5];
                    [dic setObject:autoId forKey:@"autoid"];
                    [dic setObject:fileName forKey:@"category"];
                    [dic setObject:colorName forKey:@"colorname"];
                    [dic setObject:[NSString stringWithFormat:@"%@/%@.png",img360Path,fileName] forKey:@"categoryimg"];
                    
                    NSMutableArray * img360Array = [NSMutableArray array];
                    
                    NSArray * imgArray = [fileManager contentsOfDirectoryAtPath:path error:&error];
                    for(NSString * img in imgArray)
                    {
                        if([img hasSuffix:@"jpg"]||[img hasSuffix:@"png"])
                        {
                            [img360Array addObject:[NSString stringWithFormat:@"%@/%@",path,img]];
                        }
                    }
                    [dic setObject:img360Array forKey:@"360imgs"];
                    [result addObject:dic];
                }
            }
        }
        else
        {
            for (NSInteger index=0; index < [files count]; index++)
            {
                NSString* fileName = [files objectAtIndex:index];
                
                NSString *path = [img360Path stringByAppendingPathComponent:fileName];
                
                if([self isDirectoryExist:path])
                {
                    NSMutableDictionary * dic = [NSMutableDictionary dictionaryWithCapacity:5];
                    [dic setObject:autoId forKey:@"autoid"];
                    [dic setObject:fileName forKey:@"category"];
                    [dic setObject:@"" forKey:@"colorname"];
                    [dic setObject:[NSString stringWithFormat:@"%@/%@.png",img360Path,fileName] forKey:@"categoryimg"];
                    
                    NSMutableArray * img360Array = [NSMutableArray array];
                    
                    NSArray * imgArray = [fileManager contentsOfDirectoryAtPath:path error:&error];
                    for(NSString * img in imgArray)
                    {
                        if([img hasSuffix:@"jpg"]||[img hasSuffix:@"png"])
                        {
                            [img360Array addObject:[NSString stringWithFormat:@"%@/%@",path,img]];
                        }
                    }
                    [dic setObject:img360Array forKey:@"360imgs"];
                    [result addObject:dic];
                }
            }
        }
        
        
        
    }
    return [result autorelease];
}
//得到某个车型的360度内饰数据
-(NSArray*)get360Inside:(NSString*)autoId
{
    
    NSDictionary * autoDic = [autoDictionary objectForKey:autoId];
    NSString * img360Path = [NSString stringWithFormat:@"%@/360_Inside",[autoDic objectForKey:@"autopath"]];
    
    if(![self isDirectoryExist:img360Path])
        return nil;
    
    NSMutableArray * result = [NSMutableArray new];
    
    NSError *error = nil;
    
    NSArray* files = [fileManager contentsOfDirectoryAtPath:img360Path error:&error];
    
    if(error == nil)
    {
        for (NSInteger index=0; index < [files count]; index++)
        {
            NSString* fileName = [files objectAtIndex:index];
            
            NSString *path = [img360Path stringByAppendingPathComponent:fileName];
            
            if([self isDirectoryExist:path])
            {
                NSMutableDictionary * dic = [NSMutableDictionary dictionaryWithCapacity:3];
                [dic setObject:autoId forKey:@"autoid"];
                [dic setObject:fileName forKey:@"category"];
                [dic setObject:[NSString stringWithFormat:@"%@/%@.png",img360Path,fileName] forKey:@"categoryimg"];
                
                NSMutableArray * img360Array = [NSMutableArray array];
                
                NSArray * imgArray = [fileManager contentsOfDirectoryAtPath:path error:&error];
                for(NSString * img in imgArray)
                {
                    if([img hasSuffix:@"jpg"]||[img hasSuffix:@"png"])
                    {
                        [img360Array addObject:[NSString stringWithFormat:@"%@/%@",path,img]];
                    }
                }
                [dic setObject:img360Array forKey:@"360imgs"];
                [result addObject:dic];
            }
        }
    }
    return [result autorelease];
}


//车型选择
-(NSArray*)getAllBrands
{
    NSMutableArray * result = [NSMutableArray new];
    FMResultSet * rs = [sqliteHelper  syncExecuteQuery:SQL_GETBRANDS];
    while([rs next])
    {
        [result addObject:[rs resultDict]];
    }
    return [result autorelease];
}

-(NSArray*)getSeriesByBrand:(NSInteger)brandId
{
    NSMutableArray * result = [NSMutableArray new];
    FMResultSet * rs = [sqliteHelper  syncExecuteQuery:[NSString stringWithFormat:SQL_GETSERIES,brandId]];
    while([rs next])
    {
        [result addObject:[rs resultDict]];
    }
    return [result autorelease];
}
-(NSArray*)getSpecBySeriesId:(NSInteger)seriesId brand:(NSInteger)brandId
{
    NSMutableArray * result = [NSMutableArray new];
    FMResultSet * rs = [sqliteHelper  syncExecuteQuery:[NSString stringWithFormat:SQL_GETSPEC,brandId,seriesId]];
    while([rs next])
    {
        [result addObject:[rs resultDict]];
    }
    return [result autorelease];
}

-(NSInteger)getHondaCar:(NSString*)autoNameKey
{ 
    FMResultSet * rs = [sqliteHelper  syncExecuteQuery:[NSString stringWithFormat:SQL_GETHONDACAR,autoNameKey]];
    if([rs next])
    {
        return [[[rs resultDict]objectForKey:@"specid"]intValue];
    }
    return 0;
}

// 品牌故事：荣誉概要
-(NSArray*) getBrandHonor:(NSString*) filePath{
    NSMutableArray * result = [NSMutableArray new];
    if ([self isFileExist:filePath]) {
        NSData * data = [NSData dataWithContentsOfFile:filePath];
        NSDictionary * dic = [data objectFromJSONData];
        [result addObjectsFromArray:[dic objectForKey:@"Contents"]];
        
    }
    
    return [result autorelease];
}

#pragma Common

-(BOOL)isFileExist:(NSString*)filePath
{
	BOOL isDirectory = NO;
	BOOL result = [fileManager fileExistsAtPath:filePath isDirectory:&isDirectory];
	return result&!isDirectory;
}

-(BOOL)isDirectoryExist:(NSString*)directoryPath
{
	BOOL isDirectory = NO;
	BOOL result = [fileManager fileExistsAtPath:directoryPath isDirectory:&isDirectory];
	return result&isDirectory;
}

-(void)dealloc
{
    SafeRelease(sqliteHelper);
    SafeRelease(fileManager);
    SafeRelease(autoDictionary);
    [super dealloc];
}

@end
